<?php

class IndexAction extends CommonAction
{
    private static $configs = array();

    private static $instance;
    const host = '127.0.0.1';
    const port = '6379';
    const timeout = 300;
    const auth = '';
    const shuqian_key = 'shuqian_redpack_list';

    public static function getRedisInstance()
    {
        if (self::$instance) {
            return self::$instance;
        }
        try {
            $redis = new \Redis();
            $con = $redis->connect(self::host, self::port, self::timeout);

            if (false == $con) {
                throw new \Exception('connect redis fail');
            }
            if (self::auth) {
                $success = $redis->auth(self::auth);
                if (false == $success) {
                    throw new \Exception('redis auth fail');
                }
            }
            $sel = $redis->select(0);
            if (false == $sel) {
                throw new \Exception('select db fail');
            }
            return self::$instance = $redis;
        } catch (Exception $ex) {
            throw new \Exception('Redis error - ' . $ex->getMessage());
        }
    }

    //显示排行榜
    public function showList()
    {

        include "./Home/Runtime/setting.config.php";
        self::$configs = $configs;

        $Score = D('Score');
        $scoreData = $Score->relation('User')->order('score desc')->select();
        $this->assign('scoreData', $scoreData);
        //$Config = M('Config');
        //获取微信分享图片，分享标题，分享描述，分享URL
        $cfg_wx_share_title = self::$configs['cfg_wx_share_title'];
        //$cfg_wx_share_title = $Config->where("varname='cfg_wx_share_title'")->getField('value');
        $this->assign('cfg_wx_share_title', $cfg_wx_share_title);

        $cfg_wx_share_desc = self::$configs['cfg_wx_share_desc'];
        //$cfg_wx_share_desc = $Config->where("varname='cfg_wx_share_desc'")->getField('value');
        $this->assign('cfg_wx_share_desc', $cfg_wx_share_desc);

        $cfg_wx_share_pic = self::$configs['cfg_wx_share_pic'];
        //$cfg_wx_share_pic = $Config->where("varname='cfg_wx_share_pic'")->getField('value');
        //$this->assign('cfg_wx_share_pic',$baseDomain."Public/Uploads/".$cfg_wx_share_pic);
        $this->assign('cfg_wx_share_pic', $cfg_wx_share_pic);

        $cfg_wx_share_url = self::$configs['cfg_wx_share_url'];
        //$cfg_wx_share_url = $Config->where("varname='cfg_wx_share_url'")->getField('value');
        $this->assign('cfg_wx_share_url', $cfg_wx_share_url);

        $cfg_wx_share_redirect = self::$configs['cfg_wx_share_redirect'];
        //$cfg_wx_share_redirect = $Config->where("varname='cfg_wx_share_redirect'")->getField('value');
        $this->assign('cfg_wx_share_redirect', $cfg_wx_share_redirect);

        $cfg_appid = self::$configs['cfg_appid'];
        $cfg_screct = self::$configs['cfg_screct'];
        // 获取分享的签名 开始
        vendor("WeixinShare.jssdk");
        $jssdk = new JSSDK($cfg_appid, $cfg_screct);
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage', $signPackage);

        $this->display();
    }


    public function index()
    {
        include "./Home/Runtime/setting.config.php";
        self::$configs = $configs;
        //$Config = M('Config');
        $User = M('User');
        $uploadDir = "__PUBLIC__/Uploads/";

        //获取微信分享图片，分享标题，分享描述，分享URL
        $cfg_wx_share_title = self::$configs['cfg_wx_share_title'];
        //$cfg_wx_share_title = $Config->where("varname='cfg_wx_share_title'")->getField('value');
        $this->assign('cfg_wx_share_title', $cfg_wx_share_title);

        $cfg_wx_share_desc = self::$configs['cfg_wx_share_desc'];
        //$cfg_wx_share_desc = $Config->where("varname='cfg_wx_share_desc'")->getField('value');
        $this->assign('cfg_wx_share_desc', $cfg_wx_share_desc);

        $cfg_wx_share_pic = self::$configs['cfg_wx_share_pic'];
        //$cfg_wx_share_pic = $Config->where("varname='cfg_wx_share_pic'")->getField('value');
        //$this->assign('cfg_wx_share_pic',$baseDomain."Public/Uploads/".$cfg_wx_share_pic);
        $this->assign('cfg_wx_share_pic', $cfg_wx_share_pic);

        $cfg_wx_share_url = self::$configs['cfg_wx_share_url'];
        //$cfg_wx_share_url = $Config->where("varname='cfg_wx_share_url'")->getField('value');
        $this->assign('cfg_wx_share_url', $cfg_wx_share_url);

        $cfg_wx_share_redirect = self::$configs['cfg_wx_share_redirect'];
        //$cfg_wx_share_redirect = $Config->where("varname='cfg_wx_share_redirect'")->getField('value');
        $this->assign('cfg_wx_share_redirect', $cfg_wx_share_redirect);

        $cfg_appid = self::$configs['cfg_appid'];
        $cfg_screct = self::$configs['cfg_screct'];
        $cfg_oauth_cb_url = self::$configs['cfg_oauth_cb_url'];
        //$cfg_appid = $Config->where("varname='cfg_appid'")->getField('value');
        //$cfg_screct = $Config->where("varname='cfg_screct'")->getField('value');
        //$cfg_oauth_cb_url = $Config->where("varname='cfg_oauth_cb_url'")->getField('value');

        //获取首页的标题
        $cfg_homepage_title = self::$configs['cfg_homepage_title'];
        //$cfg_homepage_title = $Config->where("varname='cfg_homepage_title'")->getField('value');
        $this->assign('cfg_homepage_title', $cfg_homepage_title);


        // 获取分享的签名 开始
        vendor("WeixinShare.jssdk");
        $jssdk = new JSSDK($cfg_appid, $cfg_screct);
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage', $signPackage);
        // 获取分享的签名 结束

        $isAllowOrigin = $this->isAllowedOrigin();
        if ($isAllowOrigin) {
            if (strpos($cfg_oauth_cb_url, '?') !== false) {
                $cfg_oauth_cb_url = $cfg_oauth_cb_url . '&verify=pass';
            } else {
                $cfg_oauth_cb_url = $cfg_oauth_cb_url . '?verify=pass';
            }
        }

        //判断活动是否结束
        if ($this->isGameEnd()) {

            $cfg_game_finish = self::$configs['cfg_game_finish'];
            //$cfg_game_finish=$Config->where("varname='cfg_game_finish'")->getField('value');


            $this->assign('cfg_game_finish', $cfg_game_finish);

            $this->display('gameFinish');
            exit;
        } else {


            $need_login = 1; //默认要登录
            $cookieName = "shuqianCookie";
            $shuqianCookie = $_COOKIE[$cookieName];
            //$shuqianCookie = "opM3WwRcn9aJyXdnB-JFIvE0IgJ8";//TEST
            if ($shuqianCookie != "") { // 用户玩过该游戏才可能存在cookie，非首次体验

                if (!empty($shuqianCookie)) {

                    // 判断wxid是否已经配置过，如果存在并且填写过信息，则不需要显示填写信息框
                    $condition['wxid'] = $shuqianCookie;
                    $userList = $User->where($condition)->find();

                    if ($userList && count($userList) > 0) {
                        $userphone = $userList['userphone'];
                        if (!empty($userphone) && $userphone != 'none') {
                            $need_login = 0; //表示填写过信息，不需要显示填写信息框
                        }

                        $openid = $shuqianCookie;
                        session("wxid", $openid);

                        //获取用户ID
                        $uid = $userList['id'];
                        session("uid", $uid);

                    }

                }

            }


            //授权判断
            if (empty($openid)) {
                if (empty($_REQUEST["code"])) {
                    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $cfg_appid . "&redirect_uri=" . $cfg_oauth_cb_url . "&response_type=code&scope=snsapi_base&state=blinq#wechat_redirect";
                    redirect($url);

                } else {
                    $code = $_REQUEST['code'];

                    $accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $cfg_appid . "&secret=" . $cfg_screct . "&code=$code&grant_type=authorization_code";
                    $ch = curl_init($accessTokenUrl);
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    //curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:21.0) Gecko/20100101 Firefox/21.0');
                    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    $info = curl_exec($ch);
                    $dataJson = json_decode($info, true);
                    $openid = $dataJson['openid'];
                    $access_token = $dataJson['access_token'];
                    session("wxid", $openid);


                    $cookieStr = $openid;
                    $this->setCookieVal($cookieStr);


                    // 判断wxid是否已经配置过，如果存在并且填写过信息，则不需要显示填写信息框
                    $condition['wxid'] = $openid;
                    $userList = $User->where($condition)->find();

                    //$this->assign("headimgurl",$info);

                    if ($userList && count($userList) > 0) {
                        $userphone = $userList['userphone'];
                        if (!empty($userphone) && $userphone != 'none') {
                            $need_login = 0; //表示填写过信息，不需要显示填写信息框
                        } else {
                            $need_login = 1;  //需要注册
                        }

                        //获取用户ID
                        $uid = $userList['id'];
                        session("uid", $uid);

                    } else {
                        $need_login = 1;  //需要注册

                    }

                }
            }
        }


        if ($openid) {
            $wxUser = [
                'wxid' => $openid
            ];
            if ($User->where($wxUser)->find()) {

            } else {
                $wxUser['regtime'] = date('Y-m-d H:i:s');
                $User->add($wxUser);
            }
        } else {
            if (isset($_GET['code'])) {
                $this->clearUrlCode();
            } else {
                $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $cfg_appid . "&redirect_uri=" . $cfg_oauth_cb_url . "&response_type=code&scope=snsapi_base&state=blinq#wechat_redirect";
                redirect($url);
                exit('user error');
            }
        }
        $this->checkOrigin();
        $this->clearUrlCode();

        $this->assign('need_login', $need_login);
        $this->assign('pass_score', self::$configs['cfg_pass_score']);
        $this->assign('time_limit', self::$configs['cfg_pass_time']);

        $this->display();

    }

    private function clearUrlCode()
    {
        if (isset($_GET['code']) || isset($_GET['verify'])) {
            unset($_GET['code']);
            unset($_GET['verify']);
            $queryString = '';
            if (!empty($_GET)) {
                foreach ($_GET as $key => $value) {
                    if (!is_array($value)) {
                        $queryString .= $key . '=' . urlencode($value) . '&';
                    }
                }
            }
            $queryString = rtrim($queryString, '&');
            if ($queryString) {
                $queryString = '?' . $queryString;
            }
            $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $queryString;
            header('location:' . $url);
            exit;
        }
    }

    // 保存分数
    public function saveScore()
    {
        header('Content-type: application/json');
        include "./Home/Runtime/setting.config.php";
        self::$configs = $configs;
        $score = I('post.score');
        if (isset($configs['cfg_pass_score']) && $configs['cfg_pass_score'] > 0) {
            if ($score < $configs['cfg_pass_score']) {
                exit(json_encode(['code' => 0, 'msg' => '你的成绩还没通关呢，继续努力吧']));
            }
        }
        $wxid = session('wxid');
        if (!$wxid) {
            exit(json_encode(['code' => 0, 'msg' => '登陆状态失效']));
        }
        $findUser = M('User')->where(['wxid' => $wxid])->find();
        if (!$findUser) {
            session('wxid', null);
            exit(json_encode(['code' => 0, 'msg' => '用户信息不存在，请重新进入游戏']));
        }
        // 随机抽取一个红包金额
        $bill = M('Redpack')->where(['wxid' => $wxid])->find();
        if ($bill) {
            if ($bill['score'] < $score) {
                M('Redpack')->where(['id' => $bill['id']])->save(['score' => $score]);
            }
            exit(json_encode(['code' => 200, 'msg' => 'success', 'bill_id' => $bill['id'], 'data' => $bill]));

        } else {
            $redis = self::getRedisInstance();
            $amount = $redis->rPop(self::shuqian_key);
            if (!$amount || $amount < 1) {
                exit(json_encode(['code' => 0, 'msg' => '红包已被领完，谢谢参与']));
            }

            $newBill = [
                'wxid' => $wxid,
                'amount' => $amount,
                'score' => $score,
                'created' => date('Y-m-d H:i:s')
            ];
            $newBillId = M('Redpack')->add($newBill);
            if ($newBillId) {
                $bill = M('Redpack')->where(['id' => $newBillId])->find();
                exit(json_encode(['code' => 200, 'msg' => 'success', 'bill_id' => $newBillId, 'data' => $bill]));
            } else {
                exit(json_encode(['code' => 0, 'msg' => '红包已被领完，谢谢参与']));
            }
        }
    }

    // 打开红包(调红包接口发红包)
    public function doLuck()
    {
        header('Content-type: application/json');
        $billId = I('bill_id');
        $bill = M('Redpack')->where(['id' => $billId])->find();
        if (!$bill) {
            exit(json_encode(['code' => 0, 'msg' => '参数错误，红包不存在']));
        }
        if ($bill['wxid'] !== session('wxid')) {
            exit(json_encode(['code' => 0, 'msg' => '无效参数，登陆状态出错，请重新进入']));
        }
        if ($bill['status'] == 1) {
            exit(json_encode(['code' => 201, 'msg' => '红包已发放', 'data' => $bill]));
        }

        include "./Home/Runtime/setting.config.php";
        self::$configs = $configs;
        $cfg_appid = self::$configs['cfg_appid'];
        $cfg_screct = self::$configs['cfg_screct'];
        if ($bill['amount'] < 1) {
            exit(json_encode(['code' => 0, 'msg' => '未中奖,谢谢参与']));// 其实是参数无效
        }

        // 获取分享的签名 开始
        vendor("WeixinShare.jssdk");
        $jssdk = new JSSDK($cfg_appid, $cfg_screct);
        $redpack_amount = $bill['amount'] * 100;//单位是"分"
        $response = $jssdk->sendLingQian($bill['id'], $bill['wxid'], $redpack_amount);
        if (isset($response['result_code'], $response['partner_trade_no'])) {
            $updateData = [
                'remark' => $response['result_code'] . '' . (string)$response['return_msg'],
                'updated' => date('Y-m-d H:i:s')
            ];
            if ($response['result_code'] == 'SUCCESS') {
                $updateData['status'] = 1;
            }
            $bill = M('Redpack')->where(['id' => $response['partner_trade_no']])->find();
            if ($bill) {
                M('Redpack')->where(['id' => $bill['id']])->save($updateData);
            }
            if ($response['result_code'] == 'SUCCESS') {
                $data = M('Redpack')->where(['id' => $bill['id']])->find();
                exit(json_encode(['code' => 200, 'data' => $data]));
            } else {
                exit(json_encode(['code' => 0, '红包都被领完啦，谢谢参与!']));
            }
        } else {
            exit(json_encode(['code' => 0, 'msg' => '服务出错！']));
        }
    }

    private function checkOrigin()
    {
        $origin = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        if (!self::$configs) {
            include "./Home/Runtime/setting.config.php";
            self::$configs = $configs;
        }
        if (self::$configs['cfg_allow_reference'] && strpos($origin, self::$configs['cfg_allow_reference']) !== false) {
            // 是有效来源
        } elseif (isset($_GET['verify']) && $_GET['verify'] == 'pass') {
            // 也认为是有效来源
        } else {
            if (self::$configs['cfg_jump_page']) {
                header('location:' . self::$configs['cfg_jump_page']);
                exit;
            }
        }
    }

    private function isAllowedOrigin()
    {
        $origin = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        if (!self::$configs) {
            include "./Home/Runtime/setting.config.php";
            self::$configs = $configs;
        }
        if (self::$configs['cfg_allow_reference'] && strpos($origin, self::$configs['cfg_allow_reference']) !== false) {
            return true;
        } else {
            return false;
        }
    }

    //执行成绩记录
    public function doInput()
    {
        extract($_POST);

        $User = M('User');
        $ScoreM = M('Score');
        // $condition['username'] = $name;
        // $condition['userphone'] = $phone;
        $condition['wxid'] = $_SESSION['wxid'];
        $data = $User->where($condition)->find();
        if ($data) {
            $scoreData = $ScoreM->where('uid=' . $data['id'])->find();
            if ($score > $scoreData['score']) {
                $ScoreM->score = $score;
                $ScoreM->joindate = date("Y-m-d H:i:s");
                $rzt = $ScoreM->where('uid=' . $data['id'])->save();
                if ($rzt > 0) {
                    echo json_encode("已保存最新成绩！");
                    exit;
                } else {
                    echo json_encode("保存失败！");
                    exit;
                }

            } else {
                echo json_encode("已保存最高成绩！");
                exit;
            }
        } else {
            $data1['username'] = $name;
            $data1['userphone'] = $phone;
            $data1['wxid'] = $_SESSION['wxid'];
            $data1['regtime'] = date("Y-m-d H:i:s");
            $lastId = $User->add($data1);
            if ($lastId > 0) {
                $data2['uid'] = $lastId;
                $data2['joindate'] = date("Y-m-d H:i:s");
                $data2['score'] = $score;
                $rzt = $ScoreM->add($data2);
                if ($rzt > 0) {
                    echo json_encode('恭喜，成绩保存成功！');
                    exit;
                } else {
                    echo json_encode("保存失败！");
                    exit;
                }

            } else {
                echo json_encode("保存失败！");
                exit;
            }

        }
        echo json_encode("保存失败！!");
        exit;
    }

    //显示登记界面
    public function input()
    {
        include "./Home/Runtime/setting.config.php";
        self::$configs = $configs;
        //$Config = M('Config');
        //获取微信分享图片，分享标题，分享描述，分享URL
        $cfg_wx_share_title = self::$configs['cfg_wx_share_title'];
        //$cfg_wx_share_title = $Config->where("varname='cfg_wx_share_title'")->getField('value');
        $this->assign('cfg_wx_share_title', $cfg_wx_share_title);

        $cfg_wx_share_desc = self::$configs['cfg_wx_share_desc'];
        //$cfg_wx_share_desc = $Config->where("varname='cfg_wx_share_desc'")->getField('value');
        $this->assign('cfg_wx_share_desc', $cfg_wx_share_desc);

        $cfg_wx_share_pic = self::$configs['cfg_wx_share_pic'];
        //$cfg_wx_share_pic = $Config->where("varname='cfg_wx_share_pic'")->getField('value');
        //$this->assign('cfg_wx_share_pic',$baseDomain."Public/Uploads/".$cfg_wx_share_pic);
        $this->assign('cfg_wx_share_pic', $cfg_wx_share_pic);

        $cfg_wx_share_url = self::$configs['cfg_wx_share_url'];
        //$cfg_wx_share_url = $Config->where("varname='cfg_wx_share_url'")->getField('value');
        $this->assign('cfg_wx_share_url', $cfg_wx_share_url);

        $cfg_wx_share_redirect = self::$configs['cfg_wx_share_redirect'];
        //$cfg_wx_share_redirect = $Config->where("varname='cfg_wx_share_redirect'")->getField('value');
        $this->assign('cfg_wx_share_redirect', $cfg_wx_share_redirect);

        $cfg_appid = self::$configs['cfg_appid'];
        $cfg_screct = self::$configs['cfg_screct'];
        // 获取分享的签名 开始
        vendor("WeixinShare.jssdk");
        $jssdk = new JSSDK($cfg_appid, $cfg_screct);
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage', $signPackage);
        $this->display();
    }


    public function topN()
    {
        $Config = M('Config');
        $cfg_topn_num = $Config->where("varname='cfg_topn_num'")->getField('value');
        if (!$cfg_topn_num || empty($cfg_topn_num)) {
            $cfg_topn_num = 200;
        }

        $sql = "select u.id as uid,u.username as username,u.realname as realname,u.headimgurl as headimgurl,u.userphone as userphone,u.is_exchange as is_exchange,
				s.score as score,u.wxid as wxid,u.regtime
				from tp_user u join tp_score s on u.id=s.uid order by score desc limit " . $cfg_topn_num;
        $result = $Config->query($sql);

        $hasTopn = 0;
        if ($result && count($result) > 0) {
            $hasTopn = 1;

            foreach ($result as $row) {
                if (!empty($row['userphone']) && $row['userphone'] != 'none') {
                    $row['userphone'] = substr_replace($row['userphone'], '****', 3, 4);
                } else {
                    $row['userphone'] = '未填写';
                }

                if (empty($row['username']) || $row['username'] == '') {
                    $row['username'] = "&nbsp;&nbsp;";
                }

                $data[] = $row;
            }
            //$this->assign("data", $data);
            //$this->assign("dataSize", count($data));
        }


        echo json_encode($data);
        exit;


    }

    public function showRank()
    {
        $Config = M('Config');
        $cfg_topn_num = $Config->where("varname='cfg_topn_num'")->getField('value');
        if (!$cfg_topn_num || empty($cfg_topn_num)) {
            $cfg_topn_num = 200;
        }

        $sql = "select u.id as uid,u.username as username,u.realname as realname,u.headimgurl as headimgurl,u.userphone as userphone,u.is_exchange as is_exchange,
				s.score as score,u.wxid as wxid,u.regtime
				from tp_user u join tp_score s on u.id=s.uid order by score desc limit " . $cfg_topn_num;
        $result = $Config->query($sql);
        /* echo $sql;
        exit; */
        $hasTopn = 0;
        if ($result && count($result) > 0) {
            $hasTopn = 1;

            foreach ($result as $row) {
                if (!empty($row['userphone']) && $row['userphone'] != 'none') {
                    $row['userphone'] = substr_replace($row['userphone'], '****', 3, 4);
                } else {
                    $row['userphone'] = '未填写';
                }

                if (empty($row['username']) || $row['username'] == '') {
                    $row['username'] = "&nbsp;&nbsp;";
                }

                $data[] = $row;
            }
            $this->assign("data", $data);
            $this->assign("dataSize", count($data));
        }

        $this->assign("hasTopn", $hasTopn);
        $this->assign("cfg_topn_num", $cfg_topn_num);


        //获取微信分享图片，分享标题，分享描述，分享URL
        $cfg_wx_share_title = $Config->where("varname='cfg_wx_share_title'")->getField('value');
        $this->assign('cfg_wx_share_title', $cfg_wx_share_title);

        $cfg_wx_share_desc = $Config->where("varname='cfg_wx_share_desc'")->getField('value');
        $this->assign('cfg_wx_share_desc', $_SESSION['shareDesc']);

        $cfg_wx_share_pic = $Config->where("varname='cfg_wx_share_pic'")->getField('value');
        $this->assign('cfg_wx_share_pic', $cfg_wx_share_pic);

        $cfg_wx_share_url = $Config->where("varname='cfg_wx_share_url'")->getField('value');
        $this->assign('cfg_wx_share_url', $cfg_wx_share_url);

        $cfg_wx_share_redirect = $Config->where("varname='cfg_wx_share_redirect'")->getField('value');
        $this->assign('cfg_wx_share_redirect', $cfg_wx_share_redirect);

        $cfg_appid = $Config->where("varname='cfg_appid'")->getField('value');
        $cfg_screct = $Config->where("varname='cfg_screct'")->getField('value');
        // 获取分享的签名 开始
        vendor("WeixinShare.jssdk");
        $jssdk = new JSSDK($cfg_appid, $cfg_screct);
        $signPackage = $jssdk->GetSignPackage();
        $this->assign('signPackage', $signPackage);
        // 获取分享的签名 结束

        $this->display('topN');


    }

    private function setCookieVal($cookieStr)
    {
        $cookieName = "shuqianCookie";
        // setcookie("wxidCookie4", $cookieStr, time() + 60*60*24*100);
        // setcookie("wxidCookie4", $cookieStr, time() + 2*60);
        cookie($cookieName, $cookieStr, array('expire' => 3600 * 24 * 3000));// 3600秒
    }

    public function setCookieValExpire()
    {
        $cookieName = "shuqianCookie";
        cookie($cookieName, null);
    }

    private function setCookieVal2($cookieName, $cookieStr)
    {
        // setcookie("wxidCookie4", $cookieStr, time() + 60*60*24*100);
        // setcookie("wxidCookie4", $cookieStr, time() + 2*60);
        cookie($cookieName, $cookieStr, array('expire' => 3600 * 24 * 3000));// 3600秒
    }

    public function setCookieValExpire2($cookieName)
    {
        cookie($cookieName, null);
    }

    public function setShareCount()
    {
        $Config = M('Config');
        $flag = $Config->execute("update tp_config as c set c.value=c.value+1 where c.varname='cfg_share_count'");

        if ($flag) {
            echo json_encode(array('success' => 'ok', 'msg' => '分享计数成功！'));
        } else {
            echo json_encode(array('success' => 'ng', 'msg' => '分享计数失败！'));
        }

        exit;
    }


    public function submitScore()
    {
        if (!defined('IN_SYS')) {
            echo json_encode(array('status' => 'ng', 'msg' => '非法操作，保存失败！'));
            exit;
        }

        //
        session("shareDesc", $_POST['shareDesc']);
        //

        //
        /* $User = M('User');
        $udata = $User->find($_SESSION['uid']);
        if (count($udata) > 0) {
            $is_exchange = $udata['is_exchange'];
            if ($is_exchange == '1') {
                echo json_encode(array('status'=>'ok','msg'=>'已经兑换，不能更新成绩！'));
                exit;
            }
        } */


        $Score = M("Score"); // 实例化对象
        $data = $Score->where("uid=" . $_SESSION['uid'])->find();

        $score_array['uid'] = $_SESSION['uid'];
        $score_array['score'] = $_POST['score'];
        $score_array['joindate'] = date("Y-m-d H:i:s");

        $lastId = '';
        if (count($data) > 0) {
            if (intval($data['score']) < intval($_POST['score'])) {
                $score_array['id'] = $data['id'];
                $lastId = $Score->save($score_array);
            }
        } else {
            $lastId = $Score->add($score_array);
        }


        if (!$lastId) {
            echo json_encode(array('status' => 'ng', 'msg' => '保存失败！', 'uid' => $_SESSION['uid'], 'lastId' => $_POST['score']));
            exit;
        }

        echo json_encode(array('status' => 'ok', 'msg' => '保存成功！'));
        exit;
    }

    public function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
    {
        if ($code == 'UTF-8') {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);

            if (count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
            return join('', array_slice($t_string[0], $start, $sublen));
        } else {
            $start = $start * 2;
            $sublen = $sublen * 2;
            $strlen = strlen($string);
            $tmpstr = '';

            for ($i = 0; $i < $strlen; $i++) {
                if ($i >= $start && $i < ($start + $sublen)) {
                    if (ord(substr($string, $i, 1)) > 129) {
                        $tmpstr .= substr($string, $i, 2);
                    } else {
                        $tmpstr .= substr($string, $i, 1);
                    }
                }
                if (ord(substr($string, $i, 1)) > 129) $i++;
            }
            //if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
            return $tmpstr;
        }
    }
}